(function () {
    var $ = function (id) { return document.getElementById(id) };
    var w = document.body.clientWidth - 20;
    var h = w;
    if (w > 800) { w = 800; h = 500; }
    var parent = $('canvas4');
    var canvas4 = document.createElement('canvas');
    parent.id = ''; canvas4.id = 'canvas4';
    canvas4.width = w; canvas4.height = h;
    parent.appendChild(canvas4);
    $('menu-basic').style.top = h + 10 + 'px';
    //先初始化
    fabric.filterBackend = fabric.initFilterBackend();
    fabric.Object.prototype.transparentCorners = false;
    fabric.Object.prototype.padding = 0;
    var canvas = this.__canvas = new fabric.Canvas('canvas4'),
        f = fabric.Image.filters;
    canvas.on({
        'object:selected': function () {
            fabric.util.toArray(document.getElementsByTagName('input'))
                .forEach(function (el) { el.disabled = false; })
            var filters = ['grayscale', 'invert', 'remove-color', 'sepia', 'brownie',
                'brightness', 'contrast', 'saturation', 'noise', 'vintage',
                'pixelate', 'blur', 'sharpen', 'emboss', 'technicolor',
                'polaroid', 'blend-color', 'gamma', 'kodachrome',
                'blackwhite', 'blend-image', 'hue', 'resize'];
            for (var i = 0; i < filters.length; i++) {
                $(filters[i]) && (
                    $(filters[i]).checked = !!canvas.getActiveObject().filters[i]);
            }
        },
        'selection:cleared': function () {
            fabric.util.toArray(document.getElementsByTagName('input'))
                .forEach(function (el) { el.disabled = true; })
        }
    });
    //http://r.photo.store.qq.com/psb?/V11yOm5c30oLtO/
    //wam5qtl31PlWZrpC0IQInd1JQbjBktRQYTAKPkwsIEA!/r/dN0GmGOkLAAA
    //不能处理跨域图片，1元服务器不支持中文文件
    fabric.Image.fromURL('imgs/lake1.jpg', function (img) {
        var oImg = img.set({ left: 0, top: 0 }).scale(0.25);
        canvas.add(oImg);
    });
    fabric.Image.fromURL('imgs/fox1.jpg', function (img) {
        var oImg = img.set({ left: 150, top: 100 }).scale(0.4);
        canvas.add(oImg);
    });
    var imgEle1 = document.createElement('img');
    imgEle1.src = 'imgs/mask1.png';
    var fImage = new fabric.Image(imgEle1);
    imgEle1 = null;
    fImage.scaleX = 1; fImage.scaleY = 1;
    fImage.top = 0; fImage.left = 0;
    //遮罩，打开基本
    $('image-blend').onclick = function () {
        applyFilter(20, this.checked && new f.BlendImage({
            image: fImage,
        }));
    };
    $('image-mask').onclick = function () {
        applyFilter(20, this.checked && new f.BlendImage({
            image: fImage, mode: 'mask'
        }));
    };
    $('open-basic').onclick = function () {
        $('menu-basic').style.display = 'block';
    };
    $('close-basic').onclick = function () {
        $('menu-basic').style.display = 'none';
    };
    //基本
    $('sepia').onclick = function () {
        applyFilter(3, this.checked && new f.Sepia());
    };
    $('blackwhite').onclick = function () {
        applyFilter(19, this.checked && new f.BlackWhite());
    };
    $('brownie').onclick = function () {
        applyFilter(4, this.checked && new f.Brownie());
    };
    $('vintage').onclick = function () {
        applyFilter(9, this.checked && new f.Vintage());
    };
    $('technicolor').onclick = function () {
        applyFilter(14, this.checked && new f.Technicolor());
    };
    $('polaroid').onclick = function () {
        applyFilter(15, this.checked && new f.Polaroid());
    };
    $('kodachrome').onclick = function () {
        applyFilter(18, this.checked && new f.Kodachrome());
    };
    $('invert').onclick = function () {
        applyFilter(1, this.checked && new f.Invert());
    };
    //黑白
    $('grayscale').onclick = function () {
        applyFilter(0, this.checked && new f.Grayscale());
    };
    $('average').onclick = function () {
        applyFilterValue(0, 'mode', 'average');
    };
    $('luminosity').onclick = function () {
        applyFilterValue(0, 'mode', 'luminosity');
    };
    $('lightness').onclick = function () {
        applyFilterValue(0, 'mode', 'lightness');
    };
    //亮度，对比度
    $('brightness').onclick = function () {
        applyFilter(5, this.checked && new f.Brightness({
            brightness: parseFloat($('bn-v').value)
        }));
    };
    $('bn-v').oninput = function () {
        applyFilterValue(5, 'brightness', parseFloat(this.value));
    };
    $('contrast').onclick = function () {
        applyFilter(6, this.checked && new f.Contrast({
            contrast: parseFloat($('cs-v').value)
        }));
    };
    $('cs-v').oninput = function () {
        applyFilterValue(6, 'contrast', parseFloat(this.value));
    };
    //色相，饱和度
    $('hue').onclick = function () {
        applyFilter(21, this.checked && new f.HueRotation({
            rotation: $('hue-v').value,
        }));
    };
    $('hue-v').oninput = function () {
        applyFilterValue(21, 'rotation', this.value);
    };
    $('saturation').onclick = function () {
        applyFilter(7, this.checked && new f.Saturation({
            saturation: parseFloat($('st-v').value)
        }));
    };
    $('st-v').oninput = function () {
        applyFilterValue(7, 'saturation', parseFloat(this.value));
    };
    //色偏
    $('gamma').onclick = function () {
        var v1 = parseFloat($('gm-red').value);
        var v2 = parseFloat($('gm-green').value);
        var v3 = parseFloat($('gm-blue').value);
        applyFilter(17, this.checked && new f.Gamma({
            gamma: [v1, v2, v3]
        }));
    };
    $('gm-red').oninput = function () {
        var current = getFilter(17).gamma;
        current[0] = parseFloat(this.value);
        applyFilterValue(17, 'gamma', current);
    };
    $('gm-green').oninput = function () {
        var current = getFilter(17).gamma;
        current[1] = parseFloat(this.value);
        applyFilterValue(17, 'gamma', current);
    };
    $('gm-blue').oninput = function () {
        var current = getFilter(17).gamma;
        current[2] = parseFloat(this.value);
        applyFilterValue(17, 'gamma', current);
    };
    //噪化，马赛克
    $('noise').onclick = function () {
        applyFilter(8, this.checked && new f.Noise({
            noise: parseInt($('ns-v').value, 10)
        }));
    };
    $('ns-v').oninput = function () {
        applyFilterValue(8, 'noise', parseInt(this.value, 10));
    };
    $('pixelate').onclick = function () {
        applyFilter(10, this.checked && new f.Pixelate({
            blocksize: parseInt($('px-v').value, 10)
        }));
    };
    $('px-v').oninput = function () {
        applyFilterValue(10, 'blocksize', parseInt(this.value, 10));
    };
    //模糊，锐化，浮雕
    $('blur').onclick = function () {
        applyFilter(11, this.checked && new f.Blur({
            blur: parseFloat($('br-v').value)
        }));
    };
    $('br-v').oninput = function () {
        applyFilterValue(11, 'blur', parseFloat(this.value, 10));
    };
    $('sharpen').onclick = function () {
        applyFilter(12, this.checked && new f.Convolute({
            matrix: [0, -1, 0,
                -1, 5, -1,
                0, -1, 0]
        }));
    };
    $('emboss').onclick = function () {
        applyFilter(13, this.checked && new f.Convolute({
            matrix: [1, 1, 1,
                1, 0.7, -1,
                -1, -1, -1]
        }));
    };
    //色彩混合
    $('color-blend').onclick = function () {
        applyFilter(16, this.checked && new f.BlendColor({
            color: $('blend-color').value,
            alpha: $('blend-alpha').value,
            mode: $('blend-mode').value
        }));
    };
    $('blend-color').onchange = function () {
        applyFilterValue(16, 'color', this.value);
    };
    $('blend-alpha').oninput = function () {
        applyFilterValue(16, 'alpha', this.value);
    };
    $('blend-mode').onchange = function () {
        applyFilterValue(16, 'mode', this.value);
    };
    //移除颜色
    $('remove-color').onclick = function () {
        applyFilter(2, this.checked && new f.RemoveColor({
            distance: $('r-c-d').value,
            color: $('r-c-c').value,
        }));
    };
    $('r-c-c').onchange = function () {
        applyFilterValue(2, 'color', this.value);
    };
    $('r-c-d').oninput = function () {
        applyFilterValue(2, 'distance', this.value);
    };
    function applyFilter(index, filter) {
        var obj = canvas.getActiveObject();
        obj.filters[index] = filter;
        obj.applyFilters();
        canvas.renderAll();
    }
    function getFilter(index) {
        var obj = canvas.getActiveObject();
        return obj.filters[index];
    }
    function applyFilterValue(index, prop, value) {
        var obj = canvas.getActiveObject();
        if (obj.filters[index]) {
            obj.filters[index][prop] = value;
            obj.applyFilters();
            canvas.renderAll();
        }
    }
})();